package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bairimengchang
 * @version 1.0
 * @project sky-take-out
 * @description 数据统计业务接口实现类
 * @date 2024/9/10
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取给定日期的开始时间，比如传入2024-09-10 返回 2024-09-10 00:00:00
     * @param begin 开始日期
     * @return 日期的开始时间
     */
    private LocalDateTime getBeginTime(LocalDate begin) {
        return LocalDateTime.of(begin, LocalTime.MIN);
    }

    /**
     * 获取给定日期的结束时间，比如传入2024-09-10 返回 2024-09-10 23:59:59
     * @param end 结束日期
     * @return 日期的结束时间
     */
    private LocalDateTime getEndTime(LocalDate end) {
        return LocalDateTime.of(end, LocalTime.MAX);
    }

    /**
     * 获取两个日期之间的所有日期
     * @param begin 开始日期
     * @param end 结束日期
     * @return 日期list
     */
    private List<LocalDate> getBetweenDays(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        // 当开始日期和结束日期一样（查昨日数据）
        if (begin.equals(end)) {
            dateList.add(begin);
        } else {
            // 将这个日期区间的所有日期都加到dateList集合中
            for (LocalDate date = begin; date.isBefore(end); date = date.plusDays(1)) {
                dateList.add(date);
            }
        }
        log.info("dateList:{}", dateList);
        return dateList;
    }


    /**
     * 营业额统计
     * @param begin 开始日期
     * @param end 结束日期
     * @return 营业额数据统计返回的视图对象
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = getBetweenDays(begin, end);

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = getBeginTime(date);
            LocalDateTime endTime = getEndTime(date);
            log.info("beginTime:{}", beginTime);

            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            // 给定时间的营业额（某天0点到24点）
            Double turnover = ordersMapper.sumTurnoverByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            log.info("营业额：{}", turnover);

            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin 开始日期
     * @param end 结束日期
     * @return 订单统计数据视图对象
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        // 当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = getBetweenDays(begin, end);

        // 存放每日订单数
        List<Integer> orderCountList = new ArrayList<>();

        // 存放每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {

            LocalDateTime beginTime = getBeginTime(date);
            LocalDateTime endTime = getEndTime(date);

            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            // 查询当天的有效订单数（已完成）
            Integer validOrderCount = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);

            // 获取当天的订单总数
            map.put("status", null);
            Integer totalOrderCount = ordersMapper.countByMap(map);
            orderCountList.add(totalOrderCount);

        }

        Map<String, Object> map = new HashMap<>();
        // 获取总订单数
        Integer totalOrderCount = ordersMapper.countByMap(null);
        log.info("总订单数：{}", totalOrderCount);

        // 获取总有效订单数
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = ordersMapper.countByMap(map);
        log.info("总有效订单数：{}", validOrderCount);

        // 订单完成率
        double orderCompletionRate;
        if (totalOrderCount == 0) {
            // 设置一个默认值或特殊值
            orderCompletionRate = 0.0;
        } else {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        log.info("订单完成率：{}", orderCompletionRate);


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 用户统计
     * @param begin 开始日期
     * @param end 结束日期
     * @return 用户统计数据视图对象
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = getBetweenDays(begin, end);

        // 存放总用户数
        List<Integer> totalUserList = new ArrayList<>();

        // 存放每日新增用户数
        List<Integer> newUserList = new ArrayList<>();

        dateList.forEach(date -> {
            Map<String, Object> map = new HashMap<>();

            map.put("end", getEndTime(date));
            // 获取当天总用户数（创建时间小于当天24时之前）
            Integer totalUser = userMapper.countUsersByMap(map);
            totalUserList.add(totalUser);

            map.put("begin", getBeginTime(date));
            // 获取当天新增用户数
            Integer newUser = userMapper.countUsersByMap(map);
            newUserList.add(newUser);
        });


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 销量排名top10
     * @param begin 开始日期
     * @param end 结束日期
     * @return 销量排名top10数据视图对象
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 查询一定时间范围的销量top10
        LocalDateTime beginTime = getBeginTime(begin);
        LocalDateTime endTime = getEndTime(end);

        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);

        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(map);

        // 用于存放商品名称
        List<String> names = new ArrayList<>();
        // 遍历salesTop10，获取每个元素的商品名称，并添加到names列表中
        for (GoodsSalesDTO goods : salesTop10) {
            names.add(goods.getName());
        }
        String nameList = StringUtils.join(names, ",");

        // 用于存放商品数量
        List<Integer> numbers = new ArrayList<>();
        // 遍历salesTop10，获取每个元素的商品数量，并添加到numbers列表中
        for (GoodsSalesDTO goods : salesTop10) {
            numbers.add(goods.getNumber());
        }
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }
}
